import xhr from 'xhr'
import qs from 'qs'
const noop = _ => _;
const defaultConfig = {
  method: 'GET',
  useXDR: false,
  sync: false,
  json: false,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  timeout: 6000
}

const appendParam = (url, param) => {
  const hasParam = ~url.indexOf('?')
  return url + (hasParam ? '&' : '?') + qs.stringify(param)
}

const request = (url, config) => {
  const {
    success = noop, error = noop, ...others
  } = config

  const options = {
    ...defaultConfig,
    ...others
  }
  options.body = qs.stringify(options.body)

  if (options.cache === false && options.method.toLowerCase() === 'get') {
    url = appendParam(url, {
      _: new Date().getTime()
    })
  }

  return xhr(url, options, (err, resp, body) => {
    if (resp.statusCode === 200) {
      try {
        body = JSON.parse(body)
      } catch (e) {
        error(e, resp)
        return
      }

      success(body, resp)
    } else {
      error(err, resp)
    }
  })
}

export default request
